<?php
/**
 * @author by bilee.
 * 时间: 16/6/17 上午6:08
 * 帮达跑客APP管理后台
 */
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class BdrunpeopleController extends AdminbaseController

{
    protected $dispatch_level_model;
    function _initialize()
    {
        parent::_initialize();
        $this->dispatch_level_model = D("Common/DispatchLevel");
    }

    //管理首页
    public function user()
    {

        $formget = I('formget');
        $id=  intval(I("id"));
        $is_audit=  intval($formget["is_audit"]);
        $is_sign=  intval($formget["is_sign"]);
//        $is_incubator=  intval($formget["is_incubator"]);
        $job_number=  $formget["job_number"];
        $dispatch_name=  $formget["dispatch_name"];
        $is_accept_dispatch=  intval($formget["is_accept_dispatch"]);
        $company_id=  intval($formget["company_id"]);
        $mobile=  $formget["mobile"];
        $work_status = $formget['work_status'];
        $account_status = $formget['account_status'];

        $formget=array('is_audit'=>$is_audit,'is_sign'=>$is_sign,'job_number'=>$job_number
                        ,'dispatch_name'=>$dispatch_name
                        ,'is_accept_dispatch'=>$is_accept_dispatch
                        ,'company_id'=>$company_id
                        ,'mobile'=>$mobile
                        ,'work_status'=>$work_status
                        ,'account_status'=>$account_status);


        $where = " 1 " ;

        if($mobile)
            $where = $where.' and mobile like "%'.$mobile.'%"';
        if($job_number)
            $where = $where.' and job_number like "%'.$job_number.'%"';
        if($dispatch_name)
            $where = $where.' and dispatch_name like "%'.$dispatch_name.'%"';
        if($is_audit!=-1)
            $where = $where.' and is_audit = '.$is_audit;

        if($work_status!=-1)
            $where = $where.' and work_status = '.$work_status;
        if($is_sign==0||$is_sign==1)
            $where = $where.' and is_sign in( 0,1)';
        else if($is_sign==2||$is_sign==3)
            $where = $where.' and is_sign = '.$is_sign;
//        if($is_incubator!=-1)
//            $where = $where.' and is_incubator = '.$is_incubator;
        if($is_accept_dispatch!=-1)
            $where = $where.' and is_accept_dispatch = '.$is_accept_dispatch;
        if($company_id != 1)
            $where = $where.' and company_id = '.$company_id;
        if($account_status)
            $where = $where.' and account_status = '.$account_status;

        $users_model=M("dispatch d");
        $count=$users_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $users_model
                 ->field(array('weinxin_openid','jpush_id','token'),true)
          //  ->join('left join db_conveyance c ON d.conveyance_id = c.conveyance_id')
            ->where($where)
            ->order("d.dispatch_id desc")
//            ->order("d.is_audit desc,d.is_sign,d.company_id,d.job_number")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
//        $company_id = array();
//        dump($company_id );
        //die;
        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
//        echo $users_model->getLastSql();
//        dump($lists);
        $this->assign("page", $page->show('Admin'));
        $company = M('company');
        $this->assign('total_count', $count);
        $this->assign('company_data', $company->select());
        $this->display();
    }
    //审核通过未签约的跑客
    public function user_yes_audit()
    {
        $where = " 1 " ;

        $where = $where.' and is_audit = 2 and is_sign = 0';

        $users_model=M("dispatch d");

        $lists = $users_model
            ->field(array('weinxin_openid','jpush_id','token'),true)
            ->where($where)
            ->order("d.dispatch_id desc")
            ->select();

        $this->assign('lists', $lists);
        $company = M('company');
        $this->assign('company_data', $company->select());
        $this->display();
    }
    //拒绝审核通过的跑客
    public function user_no_audit()
    {
        $where = " 1 " ;

        $where = $where.' and is_audit = 3';

        $users_model=M("dispatch d");

        $lists = $users_model
            ->field(array('weinxin_openid','jpush_id','token'),true)
            ->where($where)
            ->order("d.dispatch_id desc")
            ->select();

        $this->assign('lists', $lists);
        $company = M('company');
        $this->assign('company_data', $company->select());
        $this->display();
    }
    //跑客信息查询
    public function user_sign_list()
    {

        $formget = I('formget');
        $id=  intval(I("id"));
        $is_audit=  intval($formget["is_audit"]);
        $is_sign=  intval($formget["is_sign"]);
//        $is_incubator=  intval($formget["is_incubator"]);
//        $job_number=  $formget["job_number"];
        $dispatch_name=  $formget["dispatch_name"];
//        $is_accept_dispatch=  intval($formget["is_accept_dispatch"]);
        $company_id=  intval($formget["company_id"]);
        $mobile=  $formget["mobile"];
//        $work_status = $formget['work_status'];
        $account_status = $formget['account_status'];
        $start_time=  $formget["start_time"];//开始时间
        $end_time=  $formget["end_time"];//结束时间

        $formget=array('is_audit'=>$is_audit,'is_sign'=>$is_sign
//        ,'job_number'=>$job_number
        ,'dispatch_name'=>$dispatch_name
//        ,'is_accept_dispatch'=>$is_accept_dispatch
        ,'company_id'=>$company_id
        ,'mobile'=>$mobile
//        ,'work_status'=>$work_status
        ,'account_status'=>$account_status
        ,'start_time'=>$start_time
         ,'end_time'=>$end_time);


        $where = " 1 " ;

        if($mobile)
            $where = $where.' and mobile like "%'.$mobile.'%"';
//        if($job_number)
//            $where = $where.' and job_number like "%'.$job_number.'%"';
        if($dispatch_name)
            $where = $where.' and dispatch_name like "%'.$dispatch_name.'%"';
        if($is_audit!=-1)
            $where = $where.' and is_audit = '.$is_audit;
        if(!empty($start_time))
            $where = $where." and sign_time >= '".$start_time."  00:00:00'";
        if(!empty($end_time))
            $where = $where." and sign_time <= '".$end_time." 23:59:59' ";
//        if($work_status!=-1)
//            $where = $where.' and work_status = '.$work_status;
        if($is_sign==0||$is_sign==1)
            $where = $where.' and is_sign in( 0,1)';
        else if($is_sign==2||$is_sign==3)
            $where = $where.' and is_sign = '.$is_sign;
//        if($is_incubator!=-1)
//            $where = $where.' and is_incubator = '.$is_incubator;
//        if($is_accept_dispatch!=-1)
//            $where = $where.' and is_accept_dispatch = '.$is_accept_dispatch;
        if($company_id != 1)
            $where = $where.' and company_id = '.$company_id;
        if($account_status)
            $where = $where.' and account_status = '.$account_status;

        $users_model=M("dispatch d");
        $count=$users_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,40);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $users_model
            ->field(array('weinxin_openid','jpush_id','token'),true)
            //  ->join('left join db_conveyance c ON d.conveyance_id = c.conveyance_id')
            ->where($where)
            ->order("d.dispatch_id desc")
            ->order("d.sign_time desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
//        $company_id = array();
        //die;
        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
//        echo $users_model->getLastSql();
//        dump($lists);
        $this->assign("page", $page->show('Admin'));
        $company = M('company');
        $this->assign('total_count', $count);
        $this->assign('company_data', $company->select());
        $this->display();
    }
    /**
     * 查看上传的身份证等照片资料，是否符合规定。
     * 1：通过，0：不通过。
     * 需要填写,不通过的理由 。
     * 不通过的，需要重新上传信息
     *
     **/
    public function audit(){
        $id=  intval(I("get.id"));//
        $users_model=M("dispatch d");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("dispatch_id" => $id))->find();
        if (!$data) {
            $this->error("该跑客不存在！");
        }
        //运输工具
        $conv_obj = M("conveyance");
        $conv_data=$conv_obj->field("conveyance_id,conv_name")->select();
        $convs=array();
        foreach ($conv_data as $u){
            $convs[$u['conveyance_id']]=$u;
        }
       if( $data['city_id'] ){
            $data['province_id']=getProvinceId($data['city_id']);
            $citys = getCityList($data['province_id']);
            if($citys)
                $this->assign('citys', $citys);
        }

        $province = M('province');
        $this->assign('province_data', $province->select());
        $this->assign("convs",$convs);
        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值

        $this->display();// 输出模版文件
    }

    //查看
    public function see(){
        $id=  intval(I("get.id"));//
        $users_model=M("dispatch d");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("dispatch_id" => $id))->find();
//        dump($data);
//        die;
        if (!$data) {
            $this->error("该配送员不存在！");
        }

        //运输工具
        $conv_obj = M("conveyance");
        $conv_data=$conv_obj->field("conveyance_id,conv_name")->select();
        $convs=array();
        foreach ($conv_data as $u){
            $convs[$u['conveyance_id']]=$u;
        }
        if($data['city_id'] && $data['city_id'] != '' && $data['city_id'] != 0){
            $data['city_name']=getCityName($data['city_id']);
            $data['province_name']=getProvinceNameForCity($data['city_id']);
        }

        $this->assign("convs",$convs);
        //dump($convs);
        $this->assign("formget",I('formget'));
        //dump(I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->display();// 输出模版文件
    }

    /**
     * 审核
     * 通过与否，都发信息给跑男
     */
    public function audit_post(){
        $id = intval(I("post.id"));
        $users_db=M("dispatch");//创建与数据库表对应的实例对象

        if(isset($id) ){
            if(!I("is_audit"))
                $this->error("请选择是否通过审核！");

            $dispatch_obj = $users_db->field('mobile,dispatch_id')->where('dispatch_id='.$id)->find();
            if($dispatch_obj){
               
                $data["is_audit"]=I("is_audit");
                $data["audit_idear"]=I("audit_idear");
                $data["dispatch_id"]=$id;
                $data["city_id"]=I("city_id");
                $data['audit_time']=date('Y-m-d H:i:s',time());
                if(!I("city_id")){
                    $this->error("请填写城市!!!".$users_db->getError());
                    return;
                }

                if(I("is_audit")==2)
                    $data['job_number']=I("city_id").$id;

                $msg = '遗憾的告诉您，您提供的资料审核没通过，原因是'.I("audit_idear").'，请再次提交审核资料。谢谢您的配合！';

                if(I("is_audit")==2)
                    $msg = "恭喜您，您提交的申请资料已经通过了审核！请耐心等待客服电话通知来公司培训！";

                $users_db->startTrans();
                $msg_ret = create_dispatch_message($id,'跑客资料审核情况通知',$msg,$msg,$message_id=0);
                $save_ret = $users_db->where('dispatch_id='.$id)->save($data);

                if( $msg_ret && $save_ret){
                    
                    $users_db->commit();
                    $reseon = '：'.I("audit_idear");
                    $send_ret = send_audit_sms($dispatch_obj['mobile'], I("is_audit"),$reseon);//发送审核结果短信

                    $this->success("审核成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else{
                    $users_db->rollback();
                    $this->error("审核失败！");
                }
            }else{
                $this->error("该跑客不存在".$users_db->getError());
            }
        }else {
            $this->error('数据传入失败！');
        }
    }

    //用户取消审核
    public function cancel_audit(){
        $ids=I('id');
        if(isset($ids) && I("audit")){
            $data["is_audit"]=3;
            $data["audit_idear"]='管理员取消审核';

            $app_dispatch = M("dispatch");
            $user_obj = $app_dispatch->where("dispatch_id =".$ids.' and is_audit=2 and is_sign=0')->find();
            if($user_obj){
                $ret = $app_dispatch->where("dispatch_id =".$ids)->save($data);
                if($ret){

                    $this->success("取消审核成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else {
                    $this->error("取消审核失败！");
                }
            }else {
                $this->error("无要取消审核的数据！");
            }

        }else {
            $this->error('数据传入失败！');
        }

    }
    /**
     * 签约后跑客资料的修改
     *
     **/
    public function user_edit(){
        $id=  intval(I("get.id"));//
        $users_model=M("dispatch d");//创建与数据库表对应的实例对象
        $data = $users_model->field(array('weinxin_openid','jpush_id','token'),true)->where(array("dispatch_id" => $id,'is_sign'=>2))->find();
        if (!$data) {
            $this->error("该跑客不能被修改！");
        }

        //运输工具
        $conv_obj = M("conveyance");
        $conv_data=$conv_obj->field("conveyance_id,conv_name")->where('conveyance_id='.$data['conveyance_id'])->find();

        $data['conv_name']=$conv_data['conv_name'];

        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值

        $dispatch_level = M("dispatch_level");
        $this->assign("dispatchData",$dispatch_level->select());

        $company = M('company');
        $this->assign('company_data', $company->select());

        $company_bs = getCompanyBranch($data['company_id']);

        if($company_bs)
            $this->assign('branch_data', $company_bs);
        
        $this->display();// 输出模版文件
    }

    /**
     * 签约后跑客资料的修改
     * 通过与否，都发信息给跑男
     */
    public function user_edit_post(){
        $id = intval(I("post.id"));
        $users_db=M("dispatch");//创建与数据库表对应的实例对象

        if(isset($id) ){
            $dispatch_obj = $users_db->field('mobile,dispatch_id,dispatch_level_id,growth_value,company_id,company_branch')->where('dispatch_id='.$id.' and is_audit=2')->find();

            if($dispatch_obj){
                $level = I('new_level_id');
                $company_id = I('post.company_id');
                $company_branch = I('post.company_branch');
                if(!$level)
                    $this->error("请选择跑客级别！");
                if($dispatch_obj['dispatch_level_id']==$level && $dispatch_obj['compapny_id']==$company_id && $dispatch_obj['company_branch']==$company_branch)
                    $this->error("没有任何修改！");

                $dispatch_level = M("dispatch_level l");
                $growth_value = 0;

                if( $dispatch_obj['dispatch_level_id']!=$level ){

                    //1级的经验值是0，z级的经验值是0，level=12，表示z级
                    if($level >1 && $level < 12){
                        $levels = $dispatch_level->field('dl.lowest_growth_value')
                            ->join('left join db_dispatch_level dl on dl.level_img = l.level_img-1')
                            ->where(array('l.dispatch_level_id'=>$level))->find();
                        if($levels){
                            if($levels['lowest_growth_value'])
                                $growth_value = $levels['lowest_growth_value'];
                        }
                    }
                }

                $data['growth_value']=$growth_value;
                $data['dispatch_level_id']=$level;
                $data['company_id'] = I('company_id');
                $data['company_branch'] = I('company_branch');

                $users_db->startTrans();

                $save_ret = $users_db->where('dispatch_id='.$id)->save($data);

                if($save_ret){
                    $users_db->commit();
                    $this->success("修改成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else{
                    $users_db->rollback();
                    $this->error("修改失败！");
                }
            }else{
                $this->error("该跑客不存在".$users_db->getError());
            }
        }else {
            $this->error('数据传入失败！');
        }
    }
    /**
     * 签约页面初始化
     * 初始化团队，初始化等级，经验
     **/
    public function sign(){
        $id=  intval(I("get.id"));//
        $users_model=M("dispatch d");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("dispatch_id" => $id))->find();
        if (!$data) {
            $this->error("该跑客不存在！");
        }

        if ($data['is_audit'] != 2 || $data['is_sign'] != 1) {
            $this->error("请先审核通过跑客资料！");
        }

        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $company = M('company');
        $this->assign('company_data', $company->select());
        $dispatch_level = M("dispatch_level");
        $this->assign("dispatchData",$dispatch_level->select());
        $this->display();// 输出模版文件
    }
//用户签约
    public function user_sign(){
        $id=I('post.id');
        if(isset($id)){
            $app_dispatch = M("dispatch");

            $dispatchs = $app_dispatch->field('dispatch_id,is_audit,is_incubator,dispatch_name,is_test,cash_balance')->where("dispatch_id =".$id." and is_sign = 1 and is_audit=2 and is_incubator=1")->find();
//            if($dispatchs['is_audit'] != '2'){
//                dump('sd');
//                $this->error($dispatchs['dispatch_name'].'没有审核通过，不能签约');
//            }
//            if( $dispatchs['is_incubator']!='1')
//                $this->error($dispatchs['dispatch_name'].'没有领取保温箱，不能签约');

            if(!$dispatchs)
                $this->error('不符合签约条件');

            $cash_balance = I('post.cash_balance');
            $dispatch_level_id = I('post.dispatch_level_id');
            $commpanyId = I('post.company_id');

            if(!$commpanyId || $commpanyId == 1 )
                $this->error('请选择所属跑客团队');
            if($cash_balance == null || $cash_balance == "")
                $this->error('请输入履约金');

            $dis_balance=floatval($cash_balance);
            if($dispatchs['cash_balance'])
                $dis_balance = floatval($cash_balance) + $dispatchs['cash_balance'];

            $app_dispatch->startTrans();
            $pay_method = I('pay_method');
            if($pay_method == 1 )
                $msg_pay = '缴纳';
            elseif ($pay_method == 2 )
                $msg_pay = '公司代缴';
            //签约缴纳押金，余额字段变动
            $deposit = pnOrderDetail($id,$cash_balance, 7, '签约时'.$msg_pay.'履约金'.$cash_balance.'元', 0, '履约金');//跑客余额表增加记录

            if(!$deposit)
                $this->error($dispatchs['dispatch_name']."余额记录变动失败！");

            $data  = array('is_sign'=>2,'company_id'=>$commpanyId,'dispatch_level_id'=>$dispatch_level_id
                            ,'cash_balance'=>$dis_balance,'sign_time'=>date('Y-m-d H:i:s',time())
                            ,'onlinetime'=>0,'todaytime'=>0,'company_branch'=>I('post.company_branch'));


            $dispatch_level = M("dispatch_level l");
            $growth_value = 0;
            if($dispatch_level_id >1 && $dispatch_level_id < 12){
                    $levels = $dispatch_level->field('dl.lowest_growth_value')
                        ->join('left join db_dispatch_level dl on dl.level_img = l.level_img-1')
                        ->where(array('l.dispatch_level_id'=>$dispatch_level_id))->find();
                if($levels){
                    if($levels['lowest_growth_value'])
                        $growth_value = $levels['lowest_growth_value'];
                }
            }
            $data['growth_value']=$growth_value;

            $ret = $app_dispatch->where("dispatch_id =".$id)->save($data);
            if($ret){
                $msg_ret = create_dispatch_message($id,'签约成功','恭喜您成为一名跑客！','恭喜您签约成功，成为一名自豪的跑客，奔跑吧兄弟！');
                if($dispatch_level_id != 12 ){
                    pnLevelLog($growth_value, $id, "初始经验值");
                }
                if($msg_ret){
                    $app_dispatch->commit();
                    $this->assign("formget",I('formget'));
                    $this->success($dispatchs['dispatch_name']."签约成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else{
                    $app_dispatch->rollback();
                    $this->error($dispatchs['dispatch_name']."签约失败！");
                }
            }
            else{
                $app_dispatch->rollback();
                $this->error($dispatchs['dispatch_name']."签约失败！");
            }
        }else {
            $this->error('数据传入失败！');
        }
    }

    //用户取消签约
    public function cancel_sign(){
        $dispatch_id = I('id');
        if($dispatch_id && I("unsign")){

            $app_users = M("dispatch");

            $ret = $app_users->where('dispatch_id ='.$dispatch_id.' and account_status = 2 ')->find();

            if(!$ret)
                $this->error('取消签约前，请先停用账户');

            $save_ret = $app_users->where("dispatch_id =".$dispatch_id)->save(array('is_sign'=>3,'token'=>'', 'is_test'=>0,
                'is_accept_dispatch'=>0,'is_audit'=>0,'is_incubator'=>0,'is_test'=>0));
            if ( $save_ret) {
                $this->success("取消签约成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
            } else {
                $this->error("取消签约失败！");
            }
        }else {
            $this->error('数据传入失败！');
        }
    }

    //领取保温箱
    public function incubator(){
        $id=I('id');
        if(isset($id) && I("incubator")){

            $app_users = M("dispatch");
            $data["is_incubator"]=1;
            $data["is_sign"]=1;
            $rst =$app_users->where(array("dispatch_id"=>$id))->save($data);

            if ($rst) {
                $this->success("用户领取保温箱成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
            } else {
                $this->error('用户领取保温箱失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    //用户冻结
    public function user_freezee(){
        $id = I('id');
        $free = I("freezee");
        if(isset($id) && $free){
            $dispatch_db = M("dispatch");

            if($free==2){//停用，用户余额整为0
                $dispatch_db->startTrans();
                //数据回到初始状态
                $data = array('cash_balance'=>0,
                    'onlinetime'=>0,
                    'todaytime'=>0,
                    'coin_balance'=>0,
                    'totalmileage'=>0,
                    'comp_order_num'=>0,
                    'account_status'=>intval($free),
                    'accumulatemoney'=>0,
                    'recommend_person_count'=>0,
                    'recommend_amount'=>0,
                    'evaluate_count'=>0,
                    'evaluate_star'=>0,
                    'work_status'=>0,
                    'praise'=>100,
                    'growth_value'=>0,
                    'freeze_time'=>date('Y-m-d H:i:s',time())
                );
                $dispatch_obj = $dispatch_db->field('cash_balance,growth_value,coin_balance')->where(array("dispatch_id"=>$id))->find();
                $balance_ret = 1;
                $pn_lret = 1;
                $pncoin_ret = 1;
                if($dispatch_obj['cash_balance'] > 0 )
                    $balance_ret = pnOrderDetail($id, $dispatch_obj['cash_balance']*-1, 7, '停用余额结清', 0, '停用余额结清');
                if($dispatch_obj['growth_value'] > 0 )
                    $pn_lret = pnLevelLog($dispatch_obj['growth_value']*-1, $id, '停用经验值结清');//每笔订单跑客奖励的经验值
                if($dispatch_obj['coin_balance'] > 0 )
                    $pncoin_ret = pnCoin($dispatch_obj['coin_balance'], 2, $id, '停用帮币结清', '停用帮币结清');//2：表示增加负值
                $data['token']='';
                $data['freeze_reason']='停用，数据回到初始状态';
                $rst =$dispatch_db->where(array("dispatch_id"=>$id))->save($data);

                if($balance_ret && $pn_lret && $pncoin_ret && $rst){
                    $dispatch_db ->commit();
                    $this->success("用户停用成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else{
                    $dispatch_db->rollback();
                    $this->error("用户停用失败！");
                }
            }elseif ($free==3){//冻结
                $dispatch_db->startTrans();
                $rst =$dispatch_db->where(array("dispatch_id"=>$id))->save(array('account_status'=>3,'freeze_time'=>date('Y-m-d H:i:s',time()),'freeze_reason'=>'账户异常被冻结，请联系客服'));

                if( $rst){
                    $dispatch_db ->commit();
                    $this->success("用户冻结成功！", U('Bdrunpeople/user',array('formget'=>I('formget'))));
                }else{
                    $dispatch_db->rollback();
                    $this->error("用户冻结失败！");
                }
            }

        } else {
            $this->error('数据传入失败！');
        }

    }

    /**
     * 用户重新启用
     */
    function user_again_using  ()
    {
        if (IS_POST) {
            $id = intval(I("id"));//
            $dispatch_db = M("dispatch d");//创建与数据库表对应的实例对象
            $user_obj = $dispatch_db->field(array('account_status,dispatch_name'))->where(array("dispatch_id" => $id))->find();

            if ($user_obj['account_status'] == 2) {//由冻结申请启用，启用时，初始账户余额
                $dispatch_db->startTrans();
                $level = I('new_level_id');
                if(!$level)
                    $this->error("请选择跑客级别！");

                $data=array(
                    'dispatch_level_id'=>$level
                    ,'company_id' => I('company_id')
                    ,'cash_balance' => I('cash_balance')
                    ,'account_status' => 1
                    ,'freeze_time' => date('Y-m-d H:i:s', time())
                    ,'freeze_reason' => '停用转启用'
                );
                $pay_method = I('pay_method');
                if($pay_method == 1 )
                    $msg_pay = '缴纳';
                elseif ($pay_method == 2 )
                    $msg_pay = '公司代缴';
                //签约缴纳押金，余额字段变动
                if(I('cash_balance')>0){
                    $deposit = pnOrderDetail($id,I('cash_balance'), 7, '您的账户停用转启用时'.$msg_pay.'履约金'.I('cash_balance').'元', 0, '履约金');//跑客余额表增加记录
                    if(!$deposit)
                        $this->error($user_obj['dispatch_name']."余额记录变动失败！");
                }

                $dispatch_level = M("dispatch_level l");
                $growth_value = 0;
                if($level >1 && $level < 12){
                    $levels = $dispatch_level->field('dl.lowest_growth_value')
                        ->join('left join db_dispatch_level dl on dl.level_img = l.level_img-1')
                        ->where(array('l.dispatch_level_id'=>$level))->find();
                    if($levels){
                        if($levels['lowest_growth_value'])
                            $growth_value = $levels['lowest_growth_value'];
                    }
                }
                $data['growth_value']=$growth_value;
                $save_ret = $dispatch_db->where('dispatch_id='.$id)->save($data);

                if ( $save_ret) {
                    $dispatch_db->commit();
                    $this->success("用户启用成功！", U('Bdrunpeople/user', array('formget' => I('formget'))));
                } else {
                    $dispatch_db->rollback();
                    $this->error("用户启用失败！");
                }
            }else
                $this->error("参数有误！");
        }else{
                $id=  intval(I("get.id"));//
                $dispatch_db=M("dispatch d");//创建与数据库表对应的实例对象
                $user_obj = $dispatch_db->where(array("dispatch_id" => $id))->find();

                if (!$user_obj) {
                    $this->error("该跑客不存在！");
                }
                if ($user_obj['account_status'] == 1)
                    $this->error('无需启用');
                if ($user_obj['account_status'] == 3) {//由冻结申请启用，启用时，初始账户余额
                    $rst = $dispatch_db->where(array("dispatch_id" => $id))->save(array('account_status' => 1, 'freeze_time' => date('Y-m-d H:i:s', time()), 'freeze_reason' => '停用转启用'));
                    if ($rst) {
                        $dispatch_db->commit();
                        $this->success("用户启用成功！", U('Bdrunpeople/user', array('formget' => I('formget'))));
                    } else {
                        $dispatch_db->rollback();
                        $this->error("用户启用失败！");
                    }
                }
                if ($user_obj['account_status'] == 2){
                    $dispatch_level = M("dispatch_level");
                    $this->assign("dispatchData",$dispatch_level->select());

                    $company = M('company');
                    $this->assign('company_data', $company->select());

                    $company_bs = getCompanyBranch($user_obj['company_id']);
                    $this->assign("formget",I('formget'));
                    $this->assign("data", $user_obj);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
                    if($company_bs)
                        $this->assign('branch_data', $company_bs);
                    $this->display();// 输出模版文件
                }

        }
    }
    //消息中心
    public function massage()
    {
        $this->display();
    }

    /**
     * 订单列表
     */
    public function order_list(){
        $order_model=M("order o");

        $formget = I('formget');
        $order_number=  $formget["order_number"];//订单号
        $order_type=  intval($formget["order_type"]);//订单类型
        $status=  intval($formget["status"]);//订单状态
        $job_number=  $formget["job_number"];//工号
        $dispatch_name=  $formget["dispatch_name"];//配送员姓名
        $start_time=  $formget["start_time"];//开始时间
        $end_time=  $formget["end_time"];//结束时间
//        $is_valid=$formget["is_valid"];//是否有效
        $is_reservation=$formget["is_reservation"];//是否预约单
        $mobile = $formget["mobile"];
       
        $user_model = M('app_users');
        if(!empty($mobile))
        {
            $user_id = $user_model->where("mobile =".$mobile)->getfield('user_id');
            //dump($user_id);
            
        }
        $formget =array('order_number'=>$order_number
            ,'order_type'=>$order_type,
            'status'=>$status,
            'job_number'=>$job_number,
            'user_id'=>$user_id,
            'dispatch_name'=>$dispatch_name,
//            'is_valid'=>$is_valid,
            'is_reservation'=>$is_reservation,
            'start_time'=>$start_time,
            'mobile'=>$mobile,
            'end_time'=>$end_time);

        $where = " 1=1 ";

        if(!empty($job_number))
            $where = $where." and d.job_number like '%".$job_number."%'";
        if(!empty($order_number))
            $where = $where." and o.order_number like '%".$order_number."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
       if(!empty($user_id))
            $where = $where.' and o.user_id = '.$user_id;
        if( $order_type && $order_type!=-1)
            $where = $where.' and o.order_type = '.$order_type;
        if( $status && $status!=-1)
            $where = $where.' and o.status = '.$status;
//        if( $is_valid!=-1)
//            $where = $where.' and o.is_valid = '.$is_valid;
        if( $is_reservation && $is_reservation!=-1)
            $where = $where.' and o.is_reservation = '.$is_reservation;
        if(!empty($start_time))
            $where = $where." and o.order_time >= '".$start_time."  00:00:00'";
        if(!empty($end_time))
            $where = $where." and o.order_time <= '".$end_time." 23:59:59' ";

        $count = $order_model->where($where)->join('left join db_dispatch d on d.dispatch_id = o.dispatch_id ')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $order_model
            ->field('o.order_id,o.user_id,o.city_id,o.order_number,o.order_time,o.order_type,o.status,o.pay_method,o.order_amount,o.real_amount,d.mobile,d.dispatch_name,d.job_number,o.is_valid,get_vali_code,is_reservation,is_appoint,o.total_mileage,o.finish_time')
            ->join('left join db_dispatch d on d.dispatch_id = o.dispatch_id ')
            ->where($where)
            ->order("o.order_id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();
       //echo $order_model->getLastSql();
        $city_obj = M("city_code");
        $city_data=$city_obj->field("city_id,city_name")->select();
        $citys=array();
        foreach ($city_data as $u){
            $citys[$u['city_id']]=$u;
        }

        $this->assign('total_count', $count);
        $this->assign("citys",$citys);
        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
        $this->assign("page", $page->show('Admin'));
        $this->display();
    }

    //订单查看
    public function order_show(){
        $id=  intval(I("get.id"));//
        $users_model=M("order o");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("order_id" => $id))->find();
        if (!$data) {
            $this->error("该订单不存在！");
        }

        //配送员
        $dispatch_obj = M("dispatch");
        $dispatch_data=$dispatch_obj->field("dispatch_id,dispatch_name,mobile,job_number")->select();
        $dispatchs=array();
        foreach ($dispatch_data as $u){
            $dispatchs[$u['dispatch_id']]=$u;
        }
        //城市
        $city_obj = M("city_code");
        $city_data=$city_obj->field("city_id,city_name")->select();
        $citys=array();
        foreach ($city_data as $u){
            $citys[$u['city_id']]=$u;
        }
        //运输工具
        $conv_obj = M("conveyance");
        $conv_data=$conv_obj->field("conveyance_id,conv_name")->select();
        $convs=array();
        foreach ($conv_data as $u){
            $convs[$u['conveyance_id']]=$u;
        }
        //取消事由
        $cancle_obj = M("cancle_reason");
        $cancle_data=$cancle_obj->field("cancle_reason_id,cancle_reason")->select();
        $cancles=array();
        foreach ($cancle_data as $u){
            $cancles[$u['cancle_reason_id']]=$u;
        }
        //优惠券
        $coupon_obj = M("user_coupon");
        $user_coupon_data=$coupon_obj->where(array('user_coupon_id'=>$data['coupon_id']))->field("coupon_id,coupon_type,coupon_value")->find();
        $coupon_obj=M('coupon_info')->where(array('coupon_id'=>$user_coupon_data['coupon_id']))->find();

        $data['deduct_amount']=number_format($user_coupon_data['coupon_value'],2);

        $data['coupon_type']=$coupon_obj['coupon_type'];

        $this->assign("dispatchs", $dispatchs);
        $this->assign("citys", $citys);
        $this->assign("convs", $convs);
        $this->assign("cancles", $cancles);
        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->display();// 输出模版文件
    }

    /**
     * 订单编辑页面
     **/
    public function order_edit(){
        $id=  intval(I("get.id"));//
        $users_model=M("order o");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("order_id" => $id))->find();
        if (!$data) {
            $this->error("该订单不存在！");
        }

        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值
        $this->display();// 输出模版文件
    }

    //订单编辑提交
    public function order_post(){
        $id = intval(I("post.id"));
        //dump($id);
        $data = $this->get_post_order_data();

        $users_model=M("order");//创建与数据库表对应的实例对象
        if(isset($id) ){
            $users_model->create();
            if ($data) {
                if ($users_model->save($data)!==false) {
                    $this->success("编辑成功！", U('Bdrunpeople/order',array('formget'=>I('formget'))));
                } else {
                    $this->error("编辑失败！");
                }
            } else {
                $this->error("失败".$users_model->getError());

            }
        }else {
            $this->error('数据传入失败！');
        }
    }

    public function get_post_order_data(){
        $data["order_id"]=I("id");
        $data["order_type"]=I("order_type");
        $data["special_need_id"]=I("special_need_id");
        $data["reci_mobile"]=I("reci_mobile");
        $data["reci_address"]=I("reci_address");
        $data["reci_latit"]=I("reci_latit");
        $data["reci_longit"]=I("reci_longit");
        $data["send_mobile"]=I("send_mobile");
        $data["send_address"]=I("send_address");
        $data["send_latit"]=I("send_latit");
        $data["send_longit"]=I("send_longit");
        $data["is_reservation"]=I("is_reservation");
        $data["is_incubator"]=I("is_incubator");
        $data["is_insurance"]=I("is_insurance");
        $data["insurance_amount"]=I("insurance_amount");
        $data["is_collection"]=I("is_collection");
        $data["remark"]=I("remark");
        $data["order_amount"]=I("order_amount");
        $data["real_amount"]=I("real_amount");
        $data["coupon_id"]=I("coupon_id");
        $data["total_mileage"]=I("total_mileage");
        $data["is_return_order"]=I("is_return_order");
        $data["dispatch_id"]=I("dispatch_id");
        $data["cancel_reason_id"]=I("cancel_reason_id");
        $data["cancel_party"]=I("cancel_party");
        $data["user_eval_value"]=I("user_eval_value");
        $data["disp_eval_value"]=I("disp_eval_value");
        $data["help_goods_desc"]=I("help_goods_desc");
        $data["help_goods_amount"]=I("help_goods_amount");
        $data["conveyance_id"]=I("conveyance_id");

        return $data;
    }

    //订单删除
    public function order_delete(){
        $id = intval(I("id"));
        $users_model=M("order");//创建与数据库表对应的实例对象
        if(isset($id) ){
            $data["is_valid"]=0;
            $data["order_id"]=$id;

            if ($data) {
                if ($users_model->save($data)!==false) {
                    $this->assign("formget",I('formget'));
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            } else {
                $this->error("失败".$users_model->getError());

            }
        }else {
            $this->error('数据传入失败！');
        }
    }

    //派单员余额明细查看
    public function dispatch_balance(){
        $balance_type=  intval(I("post.balance_type"));//订单类型
        $start_time=  I("post.start_time");//开始时间
        $end_time=  I("post.end_time");//结束时间
        $formget=array('order_number'=>$balance_type
        ,   'start_time'=>$start_time,
            'end_time'=>$end_time);

        $where = " 1=1 ";
        if($balance_type){
            $where = $where." and balance_type = ".$balance_type;
        }
        if($start_time)
            $where = $where.' and d.time > '.$start_time;
        if($end_time)
            $where = $where.' and d.time < '.$end_time;

        $order_model=M("dispatch_balance d");
        $count=$order_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }

        $lists = $order_model
            ->field('d.balance_id,d.time,d.dispatch_id,d.balance_type,d.balance_amount,d.change_memo,d.remark,'
                 .'case d.balance_type when 1 then order_id when 2 then order_id when 3 then coin_id when 4 then cash_record_id else "" end as order_id,'
                 .'b.job_number,b.dispatch_name,'
                 .'case d.balance_type when 1 then o.order_number when 2 then o.order_number when 3 then "" when 4 then trans_number else "" end as order_number')
            ->join('left join db_dispatch b on d.dispatch_id = b.dispatch_id left join db_order o on d.order_id = o.order_id left join db_dispatch_cash c on d.cash_record_id = c.cash_record_id')
            ->where($where)
            ->order("d.time,o.order_number desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
        $this->assign("page", $page->show('Admin'));
        $this->display();
    }

    
    /**
     * 用户级别=====================================================
     */
    function user_level(){
        $dispatch_level = M("dispatch_level");
        $this->assign("dispatchData",$dispatch_level->select());
        $this->display();
    }

    /**
     * 新增用户级别
     */
    function add_user_level(){
        if(IS_POST){
            //$dispatch_level = M("dispatch_level");
            if($this->dispatch_level_model->create()){
                $ret = $this->dispatch_level_model->add();
                if($ret!==false){
                    $this->success("新增成功！",U("user_level"));
                }else{
                    $this->error("新增失败！");
                }
            }else{
                $this->error($this->dispatch_level_model->getError());
            }
        }else{
            $this->display();
        }
    }

    /**
     * 用户级别编辑
     */
    function user_level_edit(){

        if(IS_POST){
            // 根据表单提交的POST数据创建数据对象
            if($this->dispatch_level_model->create()){
                $ret = $this->dispatch_level_model->save();
                if($ret){
                    $this->success("修改成功！",U("user_level"));
                }else{
                    $this->error("修改失败！");
                }
            }else{
                $this->error($this->dispatch_level_model->getError());
            }
        }else{
            $ret = $this->dispatch_level_model->where(array('dispatch_level_id'=>I('dispatch_level_id')))->find();
            $this->assign("dispatch_data",$ret);
            $this->display();
        }

    }

    /**
     * 用户级别删除
     */
    function user_level_del(){

            $ret = $this->dispatch_level_model->delete(I('dispatch_level_id'));
            if($ret){
                $this->success("删除成功！",U("user_level"));
            }else{
                $this->error("修改失败！");
            }
       

    }


    /**
     * 三级分销测试
     */
    function test(){
        //dump(distribution(1));
    }
    
    
    function push_server_data(){
        $order = M('order_resmsm');
        $resms = $order->where(array('order_id'=>I('order_id')))->field('order_data')->find();
        $resms_arr = json_decode($resms['order_data'],true);
        $appoints = $resms_arr;
        $appoints['city_id']=intval($resms_arr['city_id']);
        $appoints['order_type']=intval($resms_arr['order_type']);
        $appoints['order_id']=intval($resms_arr['order_id']);
        $appoints['conveyance_id']=intval($resms_arr['conveyance_id']);
        $appoints['company_id']=intval($resms_arr['company_id']);
        $appoints['user_id']=intval($resms_arr['user_id']);
        $appoints['pay_method']=intval($resms_arr['pay_method']);
        $appoints['send_longit']=doubleval($resms_arr['send_longit']);
        $appoints['send_latit']=doubleval($resms_arr['send_latit']);
        $appoints['reci_latit']=doubleval($resms_arr['reci_latit']);
        $appoints['reci_longit']=doubleval($resms_arr['reci_longit']);
        $appoints['is_reservation']=intval($resms_arr['is_reservation']);
        $appoints['is_have_price']=intval($resms_arr['is_have_price']);
        push_server_data(json_encode($appoints));
    }
    /**
     * 团队跑客批量管理
     */
    function com_dispatch_list(){

        $formget = I('formget');

        $is_sign=  intval($formget["is_sign"]);
        $job_number=  $formget["job_number"];
        $dispatch_name=  $formget["dispatch_name"];
        $company_id=  intval($formget["company_id"]);
        $is_accept_dispatch=  intval($formget["is_accept_dispatch"]);

        $formget=array('is_sign'=>$is_sign,'job_number'=>$job_number
                        ,'dispatch_name'=>$dispatch_name,'company_id'=>$company_id
                        ,'is_accept_dispatch'=>$is_accept_dispatch);

        $where = " company_id !=4 " ;

        if($job_number)
            $where = $where."and job_number like '%".$job_number."%'";
        if($dispatch_name)
            $where = $where."and dispatch_name like '%".$dispatch_name."%'";
        if($is_sign)
            $where = $where.' and is_sign = '.$is_sign;
        if($company_id!=1)
            $where = $where.' and company_id = '.$company_id;
        if($is_accept_dispatch!=-1)
            $where = $where.' and is_accept_dispatch = '.$is_accept_dispatch;

        $users_model=M("dispatch d");
        $count=$users_model->where($where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,10);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "formget[".$key."]=".urlencode($val)."&";
        }

        $lists = $users_model
            //     ->field('mobile','dispatch_name','avatar','cert_number','cert_face','cert_wrong','cert_hand','is_audit','audit_idear','is_sign','is_incubator','job_number','d.conveyance_id','c.conv_name')
            ->join('left join db_conveyance c ON d.conveyance_id = c.conveyance_id')
            ->where($where)
            ->order("d.is_audit desc,d.is_sign,d.company_id,d.job_number")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
        $this->assign("page", $page->show('Admin'));
        $company = M('company');
        $this->assign('company_data', $company->where('company_id != 4 ')->select());
        $this->display();
    }

    function com_dispatch_add(){
        $dispatch_db = M('dispatch');

        if (IS_POST) {//新增提交
            $post_data = I('post.');

            if(!$post_data)
                $this->error("请输入数据1");

            $company_id = $post_data['company_id'];
            if(!$company_id)
                $this->error("请选择所属团队！");

            if(!$post_data['data'][1]['dispatch_name'])
                $this->error("请输入姓名！");
            if(!$post_data['data'][1]['mobile'])
                $this->error("请输入手机号！");
            if(!preg_match("/^1[34578]{1}\d{9}$/",$post_data['data'][1]['mobile'])){
                $this->error("请输入正确的手机号！");
            }

            $city_id = getCompanyCity($company_id);
            
            $data = $post_data['data'];

            $mileage_count = 0;
            if($data){
                $data_arr = array();
                $dispatch_db->startTrans();
                foreach($post_data['data'] as $key=>$value){
                    if(!$value||!$value['dispatch_name']||!$value['mobile'])
                        continue;

                    if(!preg_match("/^1[34578]{1}\d{9}$/",$value['mobile'])){
                        $dispatch_db->rollback();
                        $this->error("请输入正确的手机号！");
                    }
                    $dispatch_obj = $dispatch_db->where(array('mobile'=>$value['mobile']))->find();

                    if($dispatch_obj){
                        $dispatch_db->rollback();
                        $this->error("此用户已经存在，请重新输入");
                    }

                    if(!$value['avatar']){
                        $data_arr['avatar'] = 'Uploads/public/icon.png';
                    }else if(strpos($value['avatar'],'http') ===0 )
                        $data_arr['avatar'] = $value['avatar'];
                    else
                        $data_arr['avatar'] = str_replace(__ROOT__."/", "", $value['avatar']);

                    $data_arr['company_id'] =$company_id;
                    $data_arr['city_id'] =$city_id;
                    $data_arr['dispatch_name'] =$value['dispatch_name'];
                    $data_arr['mobile'] =$value['mobile'];
                    $data_arr['token'] ='token';
                    $data_arr['conveyance_id'] =1;//$value['conveyance_id'];

                    $ret_add_bj = $dispatch_db->add($data_arr);

                    if(!$ret_add_bj){//添加失败
                        $dispatch_db->rollback();
                        $this->error("添加失败！");
                    }
                    //添加成功，继续循环
                    $mileage_count++ ;
                }
                $dispatch_db->commit();
                $this->success("添加成功",U('bdrunpeople/com_dispatch_list',array('formget'=>I('formget'))));
            }else
                $this->error("请输入数据");

        } else {// 添加页面初始化
            $company = M('company');
            $this->assign('company_data', $company->where('company_id != 4 and company_id != 1 ')->select());
            $this->display();
        }

    }
    /**
     * 修改团队跑客
     */
    function com_dispatch_edit(){

        $dispatch_db = M('dispatch');

        if (IS_POST) {

            $post_data = I('post.');
            if(!$post_data['dispatch_id'])
                $this->error("数据错误！");
            if(!$post_data['dispatch_name'])
                $this->error("请输入姓名！");
            if(!$post_data['mobile_new'])
                $this->error("请输入手机号！");
            if($post_data['mobile_new']==$post_data['mobile']){
                $this->error("您保存的是原来的手机号！");
            }

            $dispatch_obj = $dispatch_db->where(array('mobile'=>$post_data['mobile_new']))->find();

            if($dispatch_obj){
                $this->error("此用户已经存在，请重新输入");
            }else{
                $data=array(
                    'dispatch_id' => $post_data['dispatch_id'],
                    'dispatch_name' => $post_data['dispatch_name'],
                    'mobile' => $post_data['mobile_new'],
                );

                $ret = $dispatch_db->where('dispatch_id = '.$post_data['dispatch_id'])->save($data);

                if ($ret) {
                    $this->success("修改成功！", U("com_dispatch_list",array('formget'=>I('formget'))));
                } else {
                    $this->error("修改失败！");
                }
            }

        } else {

            $ret = $dispatch_db->where(array('dispatch_id' => I('dispatch_id')))->find();

            $this->assign("data", $ret);
            $this->assign("formget",I('formget'));
//            $company = M('company');
//            $this->assign('company_data', $company->where('company_id != 1 ')->select());
            $this->display();
        }
    }
    /**
     * 删除团队跑客
     */
    function com_dispatch_delete()
    {
        $sys_set_db = M('dispatch');
        $ret = $sys_set_db->where('dispatch_id='.I('dispatch_id'))->delete();

        if ($ret) {
            $this->success("删除成功！", U("com_dispatch_list",array('formget'=>I('formget'))));
        } else {
            $this->error("删除失败！", U("com_dispatch_list"));
        }
    }

    /**
     * 单人信息查询
     */
    function com_dispatch_see(){
        $dispatch_db = M('dispatch');
        $ret = $dispatch_db->where(array('dispatch_id' => I('dispatch_id')))->find();
        if(!$ret)
            $this->error("此数据不存在");


        $this->assign("data", $ret);

        $company = M('company');
        $this->assign('company_data', $company->where('company_id != 1 ')->select());
        $province = M('conveyance');
        $this->assign('conveyance_data', $province->select());
        $this->assign("formget",I('formget'));
        $this->display();

    }

    /**
     * 团队列表=================================
     */
    function company_list()
    {
        $formget = I('formget');

        $province_id=  intval($formget["city"]);
        $city_id=  $formget["city_id"];

        $formget=array('city'=>$province_id,
                        'city_id'=>$city_id
                        );

        $where = ' 1 ';

        if($province_id)
            $where =$where.' and province_id = '.$province_id;

        if($city_id)
            $where = $where.' and city_id = '.$city_id;

        $company_db = M('company');

        $count =$company_db->where($where)->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $ret = $company_db->where($where)->order('city_id,company_id')
                            ->limit($page->firstRow . ',' . $page->listRows)
                            ->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign('datas', $ret);
        $this->assign('formget', $formget);
        $province = M('province');
        $this->assign('province_data', $province->select());

        if($province_id){
            $citys = getCityList($province_id);
            $this->assign('citys', $citys);
        }

        $this->display();;
    }

    /**
     * 团队添加
     */
    function company_add()
    {
        $company_db = M('company');
        if (IS_POST) {
            $data_post = I('post.');

            $data = array('company_name'=>$data_post['company_name'],
                            'status'=>$data_post['status'],
                            'city_id'=>$data_post['city_id'],
                            'province_id'=>$data_post['province_id']
                        );

            $ret = $company_db->add($data);

            if ($ret) {
                $this->success("成功", U("bdrunpeople/company_list"));
            } else {
                $this->error("失败", $this->couponInfo->getError());
            }
        } else {
            $province = M('province');
            $this->assign('province_data', $province->select());
            $this->display();
        }

    }

    /**
     * 团队编辑
     */
    function company_edit()
    {
        $company_db = M('company');
        if (IS_POST) {
            $data_post = I('post.');
            if(!$data_post['company_id'])
                return $this->error('数据错误');
            $data = array('company_name'=>$data_post['company_name']
                            ,'status'=>$data_post['status']
                            ,'city_id'=>$data_post['city_id']
                            ,'province_id'=>$data_post['province_id']
                        );

            $ret = $company_db->where('company_id='.$data_post['company_id'])->save($data);

            if ($ret) {
                $this->success("成功", U("bdrunpeople/company_list"));
            } else {
                $this->error("失败", $this->couponInfo->getError());
            }
        } else {
            $ret = $company_db->where(array('company_id' => I('company_id')))->find();
            $this->assign('data', $ret);
            $this->assign("formget", array('formget'=>I('formget')));
            $province = M('province');
            $this->assign('province_data', $province->select());
            $citys = getCityList($ret['province_id']);
            if($citys)
                $this->assign('citys', $citys);
            $this->display();
        }
    }
    /**
     * 团队删除
     */
    function company_del()
    {
        $company_db = M('company');
        $ret = $company_db->where('company_id='.I('company_id'))->delete();
        if ($ret) {
            $this->success("删除成功！", U("company_list", array('formget'=>I('formget'))));
        } else {
            $this->error("删除失败");
        }
    }

    /**
     * 手工分配订单初始页面
     */
    function hand_appoint(){
        $order_id = I('id');
        $formget = I('formget');

        if($order_id){
            $order_db = M('order o');
            $order_obj = $order_db->field('o.*,p.voucher_no')->where(array('o.order_id'=>$order_id,'o.status'=>1))
                                  ->join('db_order_pay p on p.order_id = o.order_id')->find();
            if($order_obj){//获取已签约的跑客，没有即时单的跑客
                $dispatch_db=M('dispatch d');
                $appoint = I('appoint');
//                dump($appoint);
                $dis_name = $appoint['dis_name'];
                $dis_mobile= $appoint['mobile'];
                $dis_companyid = $appoint['company_id'];
                $where = '1';
                if($dis_name)
                    $where .=" and dispatch_name like '%".$dis_name."%'";
                if($dis_name)
                    $where .=" and mobile like '%".$dis_mobile."%'";
                if($dis_companyid && $dis_companyid != 1)
                    $where = $where.' and company_id = '.$dis_companyid;

                $count =$dispatch_db->where($where.' and is_sign =2 and account_status=1' )
                    ->count();
                import("Org.Util.Pagemumayi");
                $page = new \Pagemumayi($count,20);
                $page->parameter .='id='.$order_id.'&';
                //分页跳转的时候保证查询条件
                foreach($formget as $key=>$val) {
                    $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
                }

                $dispatch_objs = $dispatch_db->where($where.' and  is_sign =2 and account_status=1' )
                    ->field('dispatch_id,job_number,dispatch_name,mobile,company_id,city_id,place_up_time,latitude,longitude,dispatch_level_id')
                    ->limit($page->firstRow . ',' . $page->listRows)
                    ->select();
//                dump($dispatch_db->getLastSql());
                $this->assign("page", $page->show('Admin'));

                foreach($formget as $key=>$val) {
                    $page->parameter .= "formget[".$key."]=".urlencode($val)."&";
                }
                foreach($appoint as $key=>$val) {
                    $page->parameter .= "appoint[".$key."]=".urlencode($val)."&";
                }

                $this->assign('order', $order_obj);
                $this->assign("formget", I('formget'));
                $this->assign("appoint", I('appoint'));
                $this->assign('dispatchs', $dispatch_objs);
                $company = M('company');
                $this->assign('company_data', $company->select());
                $this->display();
            }else{
                $this->success("不需要指派");
            }
        }else{
            $this->error("参数有误");
        }

    }

    /**
     * 手工分配订单操作
     */
    function hand_appoint_post(){
        $voucher_no = I('voucher_no');
        $dispatch_id = I('dispatch_id');
        $order_id = I('order_id');
        $formget = I('formget');

        $pn_order_amount = getOrderAccount($order_id,$dispatch_id);//计算跑客的跑腿费

        if($pn_order_amount){
            $ret = option_pnRobOrder($voucher_no,$dispatch_id,$pn_order_amount);//分配给跑客订单

//            $up_order_ret = M('order')->where(array('order_id'=>$order_id))->setField(array('is_appoint'=>2));//手动分配  状态 转至 option_pnRobOrder 中

            $dispatch_obj = M('dispatch')->field('mobile')->where(array('dispatch_id'=>$dispatch_id))->find();//获取跑客手机号

            send_appoint_mobile($dispatch_obj['mobile']);//发短信

            if ($ret['retCode']==0) {//成功
                $rets = M('order')->field('user_id,order_number')->where(array('order_id' => $order_id))->find();
                rob_order_push($rets['user_id'], '订单（' . $rets['order_number'] . '）已被接收',array());

                $this->redirect( U("order_list",array('formget'=>I('formget'))));
            } elseif($ret['retCode']==1) {//失败
                $this->error($ret['retDesc'],  U("hand_appoint",array('id'=>$order_id)));
            }elseif ($ret['retCode']==2){//无法处理
                $this->redirect(U("order_list",array('formget'=>I('formget'))));
            }
        }else{
            $this->error("计算跑腿费失败",'');
        }
    }

    /**
     * 分公司列表
     */
    function company_branch_list()
    {
        $returns = M('company_branch')->join('db_company c on c.company_id = parent_id')->select();

        $this->assign('company_branch', $returns);
        $this->display();
    }
    /**
     * 增加分公司
     */
    function company_branch_add()
    {
        if (IS_POST) {
            $b_company_db = M("company_branch");
            $ret = M('company')->where(array('company_id' => I('parent_id')))->find();
            if ($ret) {
                $data = array(
                    'parent_id' => I('parent_id'),
                    'b_name' => I('b_name'),
                    'sort' => I('sort'),
                    'is_valid' => 1
                );
                $ret = $b_company_db->add($data);
                if ($ret) {
                    $this->success("新增成功！", U("company_branch_list"));
                } else {
                    $this->error("新增失败！", $b_company_db->getError());
                }
            } else {
                $this->error("新增失败！", $b_company_db->getError());
            }
        } else {
            $province = M('company');
            $this->assign('company_list', $province->select());
            $this->display();
        }
    }

    /**
     * 增加分公司
     */
    function company_branch_edit()
    {
        $b_company_db = M("company_branch");
        if (IS_POST) {
            $ret = M('company')->where(array('company_id' => I('parent_id')))->find();
            if ($ret) {
                $data = array(
                    'parent_id' => I('parent_id'),
                    'b_name' => I('b_name'),
                    'sort' => I('sort') //,
//                    'is_valid' => I('is_valid')
                );
                $b_ret = $b_company_db->where(array('id'=>I('id')))->save($data);
                if ($b_ret) {
                    $this->success("修改成功！", U("company_branch_list"));
                } else {
                    $this->error("修改失败！", $b_company_db->getError());
                }
            } else {
                $this->error("修改失败！", $b_company_db->getError());
            }
        } else {
            $province = M('company');
            $b_company = $b_company_db->where(array('id'=>I('id')))->find();
            $this->assign('company_list', $province->select());
            $this->assign('data', $b_company);
            $this->display();
        }
    }
    /**
     * 根据团队id获得分公司集合
     */
    function company_api()
    {
        if (IS_AJAX) {
            $location = M('company_branch');
            $ret = $location->where(array('parent_id' => I('company_id')))->order('id asc')->select();
            if ($ret) {
                RET(0, "成功", $ret);
            } else {
                RET_NO_V(1, "失败");
            }
        }
    }

    /**
     * 分公司页面初始化
     * 初始化团队，初始化等级，经验
     **/
    public function company_b(){
        $id=  intval(I("get.id"));//
        $users_model=M("dispatch d");//创建与数据库表对应的实例对象
        $data = $users_model->where(array("dispatch_id" => $id))->find();
        if (!$data) {
            $this->error("该跑客不存在！");
        }

        if ( $data['is_sign'] != 2) {
            $this->error("请先签约跑客资料！");
        }

        $this->assign("formget",I('formget'));
        $this->assign("data", $data);//在 Action 类里面使用 assign 方法对模板变量赋值，无论何种变量类型都统一使用 assign 赋值

        $this->assign('branch_data', M('company_branch')->where('parent_id='.I('company_id'))->select());

        $this->display();// 输出模版文件
    }
    //已存在用户所属分公司分配
    public function user_company_b()
    {
        $id = I('post.id');
        if (isset($id)) {
            $app_dispatch = M("dispatch");
            $dispatchs = $app_dispatch->field('dispatch_id,is_audit,is_incubator,dispatch_name,is_test,cash_balance')->where("dispatch_id =" . $id . " and is_sign =2 ")->find();

            if (!$dispatchs)
                $this->error('不符合签约条件');

            $commpany_b_id = I('post.company_branch');

            if (!$commpany_b_id || $commpany_b_id == 0)
                $this->error('请选择跑客所属分公司');

            $data = array('company_branch' => I('company_branch'));

            $ret = $app_dispatch->where("dispatch_id =" . $id)->save($data);
            if ($ret) {
                $this->assign("formget", I('formget'));
                $this->success($dispatchs['dispatch_name'] . "签约成功！", U('Bdrunpeople/user', array('formget' => I('formget'))));
            } else {
                $this->error($dispatchs['dispatch_name'] . "签约失败！");
            }
        }else {
            $this->error('数据传入失败！');
        }
    }
   /**
 * 预约转即时
 * @param $order_id
 */
function reser_to_immedi(){
    $order_id = I("id");
      if(isset($order_id)){
            $app_users = M("dispatch");
              $order_db = M('order');
              $data["is_reservation"]=1;
              $order_obj = $order_db ->where('order_id='.$order_id.' and status > 1 and status < 7')->find();
            if($order_obj){
		$up_ret = $order_db->where(array('order_id'=>$order_id))->save(array('is_reservation'=>0,'reservation_time'=>null));
		if($up_ret){
			$this->success("预约转即时成功！", U('Bdrunpeople/order_list',array('formget'=>I('formget'))));
		}else
		        $this->error('预约转即时失败！');
            }else
                {
		$this->error('数据传入失败了！');
	        }
      }else
        {
          $this->error('数据传入失败！');
        }
  }
    /**
     * 手工转单初始页面
     */
    function hand_trun(){
        $order_id = I('id');
        $formget = I('formget');

        if($order_id){
            $order_db = M('order o');
            $order_obj = $order_db->where('o.order_id='.$order_id.' and o.status >1 and o.status < 7 ')->find();
            if($order_obj){//获取已签约的跑客，没有即时单的跑客
                $dispatch_db=M('dispatch d');
                $appoint = I('appoint');
//                dump($appoint);
                $dis_name = $appoint['dis_name'];
                $dis_mobile= $appoint['mobile'];
                $dis_companyid = $appoint['company_id'];
                $where = '1';
                if($dis_name)
                    $where .=" and dispatch_name like '%".$dis_name."%'";
                if($dis_name)
                    $where .=" and mobile like '%".$dis_mobile."%'";
                if($dis_companyid && $dis_companyid != 1)
                    $where = $where.' and company_id = '.$dis_companyid;

                $count =$dispatch_db->where($where.' and is_sign =2 and account_status=1' )
                    ->count();
                import("Org.Util.Pagemumayi");
                $page = new \Pagemumayi($count,20);
                $page->parameter .='id='.$order_id.'&';
                //分页跳转的时候保证查询条件
                foreach($formget as $key=>$val) {
                    $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
                }

                $dispatch_objs = $dispatch_db->where($where.' and  is_sign =2 and account_status=1' )
                    ->field('dispatch_id,job_number,dispatch_name,mobile,company_id,city_id,place_up_time,latitude,longitude,dispatch_level_id')
                    ->limit($page->firstRow . ',' . $page->listRows)
                    ->select();
//                dump($dispatch_db->getLastSql());
                $this->assign("page", $page->show('Admin'));

                foreach($formget as $key=>$val) {
                    $page->parameter .= "formget[".$key."]=".urlencode($val)."&";
                }

                $this->assign('order', $order_obj);
                $this->assign("formget", I('formget'));
                $this->assign("appoint", I('appoint'));
                $this->assign('dispatchs', $dispatch_objs);
                $company = M('company');
                $this->assign('company_data', $company->select());
                $this->display();
            }else{
                $this->success("不需要转单");
            }
        }else{
            $this->error("参数有误");
        }
    }

    /**
     * 手工转单订单操作
     */
    function hand_trun_post(){
        $new_dispatch_id = I('dispatch_id');
        $order_id = I('order_id');
        $formget = I('formget');

        $dispatch_db = M('dispatch');
        $new_dis_obj = $dispatch_db->where(array('dispatch_id'=>$new_dispatch_id,'is_sign'=>2,'account_status'=>1))->find();
        if(!$new_dispatch_id){
            $this->error('新跑客信息有误',  U("hand_trun",array('id'=>$order_id)));
        }
        $order_db = M('order');
        $order_obj = $order_db ->where('order_id='.$order_id.'  and status > 1 and status < 7')->find();

        if(!$order_obj){
            $this->error('订单已完成或取消，不能转单',  U("hand_trun",array('id'=>$order_id)));
        }
        if( $new_dispatch_id == $order_obj['dispatch_id']){
            $this->error('跑客不能转单给自己',  U("hand_trun",array('id'=>$order_id)));
        }

        //=======临时取消保险  2016-12-29 19:01:27
        //$old_dis_count = pnrob_count($order_obj['dispatch_id'],$order_obj['order_time']);

        //if($old_dis_count == 1){//今天第一单，退还保险费
        //    $insu_ret = dispatch_insurance_options($order_obj['dispatch_id'],$order_id,2,9,'退还保险费','您今天接的第一个订单（'.$order_obj['order_number'].'）已转给其他跑客，退还保险费2.00元','您今天接的第一个订单（'.$order_obj['order_number'].'）已转给其他跑客，退还保险费2.00元');
        //}
        //$new_dis_count =  pnrob_count($new_dispatch_id,$order_obj['order_time']);

        //if($new_dis_count == 0 ){//今天第一单，扣除保险费
        //    $insu_ret = dispatch_insurance_options($new_dispatch_id, $order_id, -2, 6, '扣除保险费', '每天首次接单扣除保险费2.00元', '这是一个转单，且是您今天首次接单（' . $order_obj['order_number'] . '）扣除保险费2.00元');
        //}
        $dispatch_get_money = get_pnOrderAccount($order_id,$new_dispatch_id);

        $ret = $order_db->where(array('order_id' => $order_id))->save(array(
            //更改单子的抢单状态
            'dispatch_id' => $new_dispatch_id,
            //更改单子抢单最后时间
            'dispatch_end_time' => date('Y-m-d H:i:s'),//更新此跑客接单的时间
            'dispatch_get_money' => $dispatch_get_money
        ));

        $order_resmsm_upret = M('order_resmsm')->where(array('order_id' => $order_id))
            ->setField(array('dispatch_id' =>$new_dispatch_id ));

        $order_trun = M('order_turn')->add(array('order_id'=>$order_id,'new_dispatch_id'=>$new_dispatch_id,'old_dispatch_id'=>$order_obj['dispatch_id'],'turn_time'=>date('Y-m-d H:i:s',time()),'remark'=>'转单','trun_client'=>2,'operator_id'=>$_SESSION['ADMIN_ID']));

        $msg_ret = create_dispatch_message($new_dispatch_id, '转单', '订单（' . $order_obj['order_number'] . '）已转单给您', '订单（' . $order_obj['order_number'] . '）已转单给您，请查看订单详情');

        if($ret && $order_resmsm_upret && $order_trun && $msg_ret){
            $this->redirect( U("order_list",array('formget'=>$formget)));
        }else{
            $this->error("转单失败",  U("hand_trun",array('id'=>$order_id)));
        }
    }
    /**
     * 获取跑客团队的签约人数、听单人数、在线时长、跑客名字，完成的单数等情况
     */
    function pnall_info_list(){

        $formget = I('formget');

        $dispatch_name=  $formget["dispatch_name"];//订单号
        $mobile=  $formget["mobile"];//订单类型
        $company_id=  intval($formget["company_id"]);//订单状态

        $sign_start_time=  $formget["sign_start_time"];//开始时间
        $sign_end_time=  $formget["sign_end_time"];//结束时间

        $start_time=  $formget["start_time"];//开始时间
        $end_time=  $formget["end_time"];//结束时间
        $order_str=  $formget["order_str"];//结束时间
        if(!$start_time)
            $start_time = date('Y-m-d',time());
        if(!$end_time)
            $end_time = date('Y-m-d',time());

        if(!$order_str)
            $order_str="finish_count";
        $formget=array('dispatch_name'=>$dispatch_name
        ,'mobile'=>$mobile,
            'company_id'=>$company_id,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'sign_start_time'=>$sign_start_time,
            'sign_end_time'=>$sign_end_time,
            'order_str'=>$order_str
        );

        $where = " ";

        if( $dispatch_name)
            $where = $where." and dispatch_name like '%".$dispatch_name."%'";
        if( $mobile)
            $where = $where." and mobile like '%".$mobile."%'";
        if($company_id!=1 && $company_id != 0)
            $where = $where.' and company_id = '.$company_id;
        if(!empty($sign_start_time))
            $where = $where." and d.sign_time >='".$sign_start_time." 00:00:00'";
        if(!empty($sign_end_time))
            $where = $where." and d.sign_time <='".$sign_end_time." 23:59:59'";

        $time_where = "";
        $time_where = " and o.finish_time >= '".$start_time." 00:00:00'";
        $time_where = $time_where." and o.finish_time <= '".$end_time." 23:59:59' ";

        $dispatch_db =  M('dispatch d ');
        $count = $dispatch_db->join("left join (select o.dispatch_id,count(o.order_id) as finish_count from db_order o  where 1 ".$time_where." and status=7 group by o.dispatch_id )as order_src on order_src.dispatch_id = d.dispatch_id  ")
                                ->where(' is_sign = 2 '.$where)->count();

        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $datas = $dispatch_db->field('d.dispatch_id,d.company_id,d.company_branch,d.dispatch_name,d.mobile,d.work_status,d.is_accept_dispatch,d.onlinetime ,d.todaytime,case when order_src.finish_count is null then 0 else order_src.finish_count end as finish_count,case when order_src.finish_amount is null then 0 else order_src.finish_amount end as finish_amount ')
                                    ->join("left join (select o.dispatch_id,count(o.order_id) as finish_count,sum(o.order_amount) as finish_amount from db_order o  where 1 ".$time_where." and status=7 group by o.dispatch_id )as order_src on order_src.dispatch_id = d.dispatch_id  ")
                                    ->where(' is_sign = 2 and account_status = 1'.$where)->order('d.company_id,'.$order_str.' desc')
                                    ->limit($page->firstRow . ',' . $page->listRows)->select();

        $order_data = M('order')->field('count(*) as order_counts,status ')
                                ->where("order_time >='".$start_time." 00:00:00' and order_time <='".$end_time." 23:59:59' and status in(7,9)")
                                ->group('status')
                                ->order('status')->select();
        $this->assign("order_data", $order_data);
        $this->assign("lists", $datas);
        $this->assign("total_count",$count);
        $this->assign("formget",$formget);
        $this->assign("page", $page->show('Admin'));
        $this->assign('company_data',  M('company')->select());
        $this->display();
    }
    function pncom_info_count(){

        $datas = M('dispatch d')->field('DISTINCT d.company_id,case when d.company_branch is null then 0 else d.company_branch end as company_branch')
                                ->group('d.company_id,d.company_branch')
                                ->order('d.company_id,d.company_branch')
                                ->select();
        $this->assign("lists", $datas);
        $this->display();
    }
    public function test_order(){
        dump(pnrob_count(I('uid')));
    }
    
     /**
     * 跑客消息详情页面展示
     */
    public function dispatch_message()
    {
        $disptch_message = M("disptch_message m");
        $mobile = I("mobile");                //电话
        $dispatch_name = I("dispatch_name");  //跑客姓名
        $title = I("title");                  //消息标题
        
        $formget = array(
            'mobile' => $mobile,
            'dispatch_name' => $dispatch_name,
            'title' => $title
        );
        
        $where = "1=1";
         if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($title))
            $where = $where." and m.title like '%".$title."%'";
        
        $count = $disptch_message->where($where)->join('db_dispatch d ON m.dispatch_id=d.dispatch_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }
        $data = $disptch_message->field('d.dispatch_name,d.mobile,m.*')->join('db_dispatch d ON m.dispatch_id=d.dispatch_id')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
//        dump($data);
//        die;
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }

    /**
     * 后台取消订单，对用户和跑客都不损失
     * $this->error("参数有误");
     * @return string
     */
    function cancle_order_option()
    {
        //校验token
        $order_id = I('id');
        if (!$order_id )
            $this->error(400, "参数为空");

        //取得订单数据
        $order_db = M('order');
        $order_obj = $order_db->field('order_id,order_number,user_id,dispatch_id,order_amount,real_amount,coupon_id,status,pay_method')->where(" order_id = '" . $order_id . "' and status>1 and status <7")->find();

        if (!$order_obj)
            $this->error(400, "订单号有误");
//        dump($order_obj);

        $order_db->startTrans();
        //获取支付信息
        $recharge_db = M('order_pay');
        $pay_obj = $recharge_db->where(' order_id=' . $order_obj['order_id'])
                                ->field('pay_amount,pay_number,pay_id')->find();
        if (!$pay_obj)
            $this->error(400, "订单支付信息有误");
//        dump($pay_obj);

        //================用户方的处理 start====================
        //有优惠券处理
        $coupin_msg = "";//优惠券备注
        $is_used = 1;
        if ($order_obj['coupon_id']) {
            $is_used = M('user_coupon')->where(array('user_coupon_id' => $order_obj['coupon_id']))->save(array('is_used' => 1));//1.退还优惠券
            $coupin_msg="，优惠券退还";
            $order_amount_msg = '，订单金额是'.$order_obj['order_amount'] .'元';
        }
        if ($order_obj['pay_method'] == 1) {
            $remark_msg = '系统取消了订单(' . $order_obj['order_number'] . ')'.$order_amount_msg.'，支付宝支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元，如需要请再次下单';
        } elseif ($order_obj['pay_method'] == 2) {
            $remark_msg = '系统取消了订单(' . $order_obj['order_number'] . ')'.$order_amount_msg.'，微信支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元，如需要请再次下单';
        } elseif ($order_obj['pay_method'] == 3) {
            $remark_msg = '系统取消了订单(' . $order_obj['order_number'] . ')'.$order_amount_msg.'，钱包支付订单金额是' . $pay_obj['pay_amount'] . '元' . $coupin_msg . '，退款到用户余额 ' . $pay_obj['pay_amount'] . '元，如需要请再次下单';
        }
        $dispatch_blance_ret = 1;
        $purse_ret = 1;
        if (floatval($order_obj['real_amount']) > 0.00) {
            $purse_ret = userPurseLog($order_obj['user_id'], 3, $order_obj['real_amount'], $remark_msg, 0, $order_obj['order_id']);//用户钱包明细表 增加记录
            $dispatch_blance_ret = update_user_dispatch_blance($order_obj['user_id'], 1, $order_obj['real_amount']);//增加 用户表或跑客表的 余额字段  的值
        }
        $msg_ret = create_user_message($order_obj['user_id'], '取消订单', $remark_msg, $remark_msg);//2.给用户发取消订单消息
        //==================用户方处理 end======================================

        //==================跑客方处理 start======================================
        $pncoin_msg_ret = create_dispatch_message($order_obj['dispatch_id'], '您接的订单已被取消', '您接的订单（' . $order_obj['order_number']  . '）已被取消，请知晓', '您接的订单（' . $order_obj['order_number']  . '），已被取消，请知晓');
        //临时取消保险======2016-12-29 19:08:43
        //$insu_ret = dispatch_insurance_options($order_obj['dispatch_id'], $order_obj['order_id'], 2, 9, '退还保险费', '您今天接的第一个订单（' . $order_obj['order_number'] . '）已被取消，退还保险费2.00元', '您今天接的第一个订单（' . $order_obj['order_number']  . '）已被取消，退还您保险费2.00元');
        //==================跑客放处理  end================================================

        //=====================订单处理  start=====================
        $pay_upret = $recharge_db->where('pay_id=' . $pay_obj['pay_id'])->setField('return_status', 1);
        $data = array('status' => 9, 'cancel_time' => date('Y-m-d H:i:s', time()), 'cancel_reason_id' =>0, 'cancel_party' => 3);
        $order_upret = $order_db->where('order_id = ' . $order_obj['order_id'])->save($data);//订单状态的修改处理

        $rems_db = M('order_resmsm');
        $del_ret = $rems_db->where('order_id=' . $order_obj['order_id'])->delete();//退款成功,删除中间表order_resmsm

        $data = array( 'order_id'=>$order_id
                        ,'user_id'=>$order_obj['user_id']
                        ,'dispatch_id'=>$order_obj['dispatch_id']
                        ,'cancle_party'=>3
                        ,'order_status'=>$order_obj['status']
                        ,'remark'=>'系统取消'
                        ,'cancle_time'=>date('Y-m-d H:i:s',time())
                    );
        $add_cancle_ret = M('order_cancle')->add($data);//维护中间表---取消订单表
        //===================订单处理end =================

        if ($is_used && $dispatch_blance_ret && $purse_ret && $msg_ret && $pncoin_msg_ret && $pay_upret && $order_upret && $del_ret && $add_cancle_ret) {
//            dump('订单取消成功');
            $order_db->commit();
            $this->success('订单取消成功',U("order_list",array('formget'=>I('formget'))));
        } else {
            $order_db->rollback();
            $this->error('订单取消失败');
        }
    }

      /**
     * 跑客帮币详情页面展示
     */
    public function coin_detail()
    {
        $coin_message = M("coin_detail m");
        $mobile = I("mobile");                //电话
        $dispatch_name = I("dispatch_name");  //跑客姓名
        $get_time = I("get_time");                  //消息标题
        $get_time = substr($get_time,0,-6);
//        echo $get_time;
//        die;
        $formget = array(
            'mobile' => $mobile,
            'dispatch_name' => $dispatch_name,
            'get_time' => $get_time
        );
        
        $where = "1=1";
         if(!empty($mobile))
            $where = $where." and d.mobile like '%".$mobile."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($get_time))
            $where = $where." and m.get_time like '%".$get_time."%'";
        
        $count = $coin_message->where($where)->join('db_dispatch d ON m.dispatch_id=d.dispatch_id')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= "$key=".urlencode($val)."&";
        }
        $data = $coin_message->field('d.dispatch_name,d.mobile,m.*')->join('db_dispatch d ON m.dispatch_id=d.dispatch_id')
            ->where($where)
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign('datas',$data);
        $this->assign('page',$page->show('Admin'));
        $this->assign("formget",$formget);
        $this->display();
    }
    /**
     *设置可接单量
    **/
    function  set_pn_rob_order(){
        $dispatch_id = I("id");               
        $counts = I("counts");                
        
        $dispatch_db = M('dispatch');
        $dispatch_ret = $dispatch_db ->where('dispatch_id='.$dispatch_id)->setField('order_count',$counts);
        if($dispatch_ret){
            echo "1";
        }else{
            echo "0";
        }
    }

    /**
     * 当有退款申请时，可以做退款操作
     * 1、订单被取消，只退支付宝、微信支付的部分
     */
    function return_money_option(){
        $order_id = I("id");
        $order_db = M('order');
        $order_pay_db = M('order_pay');
        $user_db = M('app_users');

        $order_obj = $order_db->field('order_number,real_amount,user_id')->where(array('order_id'=>$order_id,'stauts'=>9,'pay_method'=>array('NEQ',3)))->find();

        $order_pay_obj = $order_pay_db->field('voucher_no,pay_amount,pay_number,pay_method')->where(array('order_id'=>$order_id,'return_status'=>1))->find();

        $user_obj = $user_db->field('purse_balance')->where(array('user_id'=>$order_obj['user_id']))->find();

        //符合退款条件
        if($order_obj && $order_pay_obj && $user_obj){
            if($order_pay_obj['pay_method']==1)//支付宝退款
            {
                $return_ret = returnMoney($order_obj['order_number'], $order_pay_obj['pay_number'], $order_pay_obj['pay_amount'],'管理员退');
                $pay_method = '支付宝';
            }elseif($order_pay_obj['pay_method']==2)//微信退款
            {
                $return_ret =returnMoneyWeixin($order_pay_obj['voucher_no'], $order_pay_obj['pay_number'], $order_pay_obj['pay_amount'], $order_pay_obj['pay_amount'], $order_obj['user_id']);
                $pay_method = '微信';
            }

            //退款成功后，做业务表处理
            if($return_ret){
                //用户表余额减少
                $user_purse_db = M('user_purse');
                $msg = '系统已将订单（'.$order_obj['order_number'].'）支付金额已原路退回到'.$pay_method.'账户';

                //用户明细表新增负值
                $data = array(
                    'purse_type' => 3,
                    'user_id' => $order_obj['user_id'],
                    'purse_amount' => round($order_pay_obj['pay_amount']*-1,2),
                    'change_time' => date('Y-m-d H-i-s', time()),
                    'change_remark' => $msg,
                    'order_id' => $order_id,
                    'sum_amount'=>get_user_balance($order_obj['user_id'])+round($order_pay_obj['pay_amount']*-1,2)
                );
                $ret_add = $user_purse_db->add($data);

                $user_up_ret  = $user_db->where(array('user_id'=>$order_obj['user_id']))->save(array('purse_balance'=>$user_obj['purse_balance']-$order_pay_obj['pay_amount']));

                //消息新增
                $msg_up_ret = create_user_message($order_obj['user_id'], '取消订单', $msg, $msg);

                //修改支付表db_order_pay的状态为3
                $pay_up_ret = $order_pay_db->where(array('order_id'=>$order_id,'return_status'=>1))->save(array('return_status'=>3));

                if($user_up_ret && $ret_add && $msg_up_ret&&$pay_up_ret)
                    $this->success('订单原路退款成功',U("order_list",array('formget'=>I('formget'))));
                else
                    $this->error('订单原路退款失败',U("order_list",array('formget'=>I('formget'))));
            }else
                $this->error($pay_method.'退款失败');
        }else
            $this->error('订单不符合退款条件');
    }

    /**
     * 转单查询列表
     */
    function order_trun_list(){
        $order_trun_db=M("order_turn t");

        $formget = I('formget');
        $order_number=  $formget["order_number"];//订单号
        $order_type=  intval($formget["order_type"]);//订单类型
        $status=  intval($formget["status"]);//订单状态
//        $job_number=  $formget["job_number"];//工号
        $dispatch_name=  $formget["dispatch_name"];//配送员姓名
        $start_time=  $formget["start_time"];//开始时间
        $end_time=  $formget["end_time"];//结束时间
//        $is_valid=$formget["is_valid"];//是否有效
        $is_reservation=$formget["is_reservation"];//是否预约单
        $mobile = $formget["mobile"];

        $user_model = M('app_users');
        if(!empty($mobile))
        {
            $user_id = $user_model->where("mobile =".$mobile)->getfield('user_id');
            //dump($user_id);

        }
        $formget =array('order_number'=>$order_number
        ,'order_type'=>$order_type,
            'status'=>$status,
//            'job_number'=>$job_number,
            'user_id'=>$user_id,
            'dispatch_name'=>$dispatch_name,
//            'is_valid'=>$is_valid,
            'is_reservation'=>$is_reservation,
            'start_time'=>$start_time,
            'mobile'=>$mobile,
            'end_time'=>$end_time);

        $where = " 1=1 ";

//        if(!empty($job_number))
//            $where = $where." and d.job_number like '%".$job_number."%'";
        if(!empty($order_number))
            $where = $where." and o.order_number like '%".$order_number."%'";
        if(!empty($dispatch_name))
            $where = $where." and d.dispatch_name like '%".$dispatch_name."%'";
        if(!empty($user_id))
            $where = $where.' and o.user_id = '.$user_id;
        if( $order_type && $order_type!=-1)
            $where = $where.' and o.order_type = '.$order_type;
        if( $status && $status!=-1)
            $where = $where.' and o.status = '.$status;
//        if( $is_valid!=-1)
//            $where = $where.' and o.is_valid = '.$is_valid;
        if( $is_reservation && $is_reservation!=-1)
            $where = $where.' and o.is_reservation = '.$is_reservation;
        if(!empty($start_time))
            $where = $where." and o.order_time >= '".$start_time."  00:00:00'";
        if(!empty($end_time))
            $where = $where." and o.order_time <= '".$end_time." 23:59:59' ";

        $count = $order_trun_db->where($where)->join('left join db_order o on t.order_id = o.order_id ') ->join('left join db_dispatch d on d.dispatch_id = o.dispatch_id ')->count();
        import("Org.Util.Pagemumayi");
        $page = new \Pagemumayi($count,20);
        //分页跳转的时候保证查询条件
        foreach($formget as $key=>$val) {
            $page->parameter .= 'formget['."$key"."]=".urlencode($val)."&";
        }

        $lists = $order_trun_db
            ->field('distinct o.dispatch_id,o.order_id,o.user_id,o.city_id,o.order_number,o.order_time,o.order_type,o.status,o.pay_method,o.order_amount,o.real_amount,get_vali_code,is_reservation,is_appoint')
            ->join('left join db_order o on t.order_id = o.order_id ')
            ->join('left join db_dispatch d on d.dispatch_id = o.dispatch_id ')
            ->where($where)
            ->order("o.order_time desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->assign('total_count', $count);
        $this->assign("formget",$formget);
        $this->assign('lists', $lists);
        $this->assign("page", $page->show('Admin'));
        $this->display();
}

    /**
     * 转单列表（弹出窗口）
     */
    function trun_list(){
        $order_trun_db=M("order_turn t");
        $order_id = I('order_id');

        $count = $order_trun_db->where(array('t.order_id'=>$order_id))->join('left join db_order o on t.order_id = o.order_id ')->count();

        $lists = $order_trun_db
            ->field('o.user_id,t.order_id,t.new_dispatch_id,t.old_dispatch_id,t.trun_client,t.operator_id,t.turn_time'.
                ',o.city_id,o.order_number,o.order_time,o.order_type,o.status,o.pay_method,o.order_amount,o.real_amount,get_vali_code,is_reservation,is_appoint')
            ->join('left join db_order o on t.order_id = o.order_id ')
            ->where(array('t.order_id'=>$order_id))
            ->order("t.turn_time ")
            ->select();
        $this->assign('total_count', $count);
        $this->assign("formget",I('formget'));
        $this->assign('lists', $lists);
        $this->display();
    }
}
